﻿using Hetang.Models.Authorize;
using Hetang.Models.DataContext;
using Hetang.Models.Classes;
using Hetang.Models.Helper;
using Hetang.Models.Interface;
using Hetang.Models.Repository;
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Hetang.Controllers
{    
    public class LoginController : Controller
    {
        IDatabaseRepository _dr;
        ISessionRepository _sr;
        ILoginRepository _lr;

        public LoginController() : this(new DatabaseRepository(), new SessionRepository(), new LoginRepository()) { }

        public LoginController(IDatabaseRepository dr,ISessionRepository sr,ILoginRepository lr)
        {
            _dr = dr;
            _sr = sr;
            _lr = lr;
        }

        public ActionResult Index(string ReturnUrl)
        {
            if (this.Request.IsAuthenticated)
            {
                if (Session["uid"] == null)
                {
                    _lr.Logout();
                    return View();
                }

                if (Url.IsLocalUrl(ReturnUrl) && ReturnUrl.Length > 1 && ReturnUrl.StartsWith("/")
                        && !ReturnUrl.StartsWith("//") && !ReturnUrl.StartsWith("/\\"))
                {
                    return Redirect(ReturnUrl);
                }
                else
                {
                    return RedirectToAction("index", "home", new { area = "" });
                }         
            }
            return View();
        }

        [HttpPost]
        public ActionResult Index(dt_Login model, string ReturnUrl)
        {            
            if (ModelState.IsValid)
            {
                tbl_Account ac = _dr.GetAccountByEmail(model.email);
                if (ac != null)
                {
                    if (ac.Password.Equals(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(model.password, "MD5")))
                    {
                        _sr.SetLoginSession(ac, true);

                        //创建一个新的票据，将客户ip记入ticket的userdata 
                        string userdata = JsonHelper.stringify(new FormsIdentityTicket { email = ac.Email, username = ac.UserName, ip = Request.UserHostAddress });
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, ac.User_Type, DateTime.Now, DateTime.Now.AddDays(30), model.remember, userdata);

                        //将票据加密 
                        string authTicket = FormsAuthentication.Encrypt(ticket);

                        //将加密后的票据保存为cookie
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket);

                        if (model.remember)
                        {
                            cookie.Expires = DateTime.Now.AddDays(30);                            
                        }

                        //使用加入了userdata的新cookie
                        Response.Cookies.Add(cookie);

                        if (Url.IsLocalUrl(ReturnUrl) && ReturnUrl.Length > 1 && ReturnUrl.StartsWith("/")
                        && !ReturnUrl.StartsWith("//") && !ReturnUrl.StartsWith("/\\"))
                        {
                            return Redirect(ReturnUrl);
                        }
                        else
                        {
                            return RedirectToAction("index", "home", new { area = "" });
                        }                        
                    }
                    else
                    {
                        ModelState.AddModelError("password", "密码错误！");
                    }
                }
                else
                {
                    ModelState.AddModelError("email", "没有这个用户！");
                }
            }
            return View(model);
        }
    }
}
